import axios from 'axios';
import { takeEvery, put  } from 'redux-saga/effects'
import { API } from '../../config';
import { USERS } from '../../consts/auth';
import { SIGNIN, SignInAction, SigninFail, SigninSuccess, SIGNUP, SignupAction, SignupFail, SignupSuccess } from '../actions/auth.actions';

export default function* authSaga() {
    yield takeEvery(SIGNUP, function* (action:SignupAction) {
        try {
            yield axios.post(`${API}/signup`, action.payload);
            yield put(SignupSuccess())
        } catch (error: any) {
            yield put(SignupFail(error.response.data.error))
        }
    })

    yield takeEvery(SIGNIN, function* (action:SignInAction) {
        try {
            const {data} = yield axios.post(`${API}/signin`,action.payload)
            localStorage.setItem(USERS,JSON.stringify(data));
            yield put(SigninSuccess())
        } catch (error: any) {
            yield put(SigninFail(error.response.data.error))

        }
    })
}